package com.bobi.tfca.ui.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.databinding.RowChatRoomLayoutBinding
import com.bobi.tfca.network.response.ChatRoomResponse
import com.bobi.tfca.ui.mainnavigation.message.MessageFragment
import com.bobi.tfca.ui.mainnavigation.message.chatroom.ChatRoomFragment
import com.bumptech.glide.Glide

class ChatRoomAdapter(val fragment: MessageFragment, var chatRoomList: ArrayList<ChatRoomResponse>) :
    RecyclerView.Adapter<ChatRoomAdapter.ChatRoomViewHolder>() {

    private var mOnItemClickListener: OnItemClickListener? = null

    interface OnItemClickListener{
        fun onItemClick(position: Int)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener?) {
        mOnItemClickListener = onItemClickListener
    }

    fun setItemList(chatRoomList: ArrayList<ChatRoomResponse>) {
        this.chatRoomList = chatRoomList
    }

    inner class ChatRoomViewHolder(private val binding: RowChatRoomLayoutBinding) : RecyclerView.ViewHolder(binding.root) {
        @SuppressLint("SetTextI18n")
        fun bind(chatRoom: ChatRoomResponse) {
            binding.chatRoom = chatRoom
            val url = chatRoom.groupHead
            if (url != null && url.isNotBlank() && (!"null".equals(url))) {
                Glide.with(fragment).load(url).placeholder(R.mipmap.default_avatar).into(binding.avatar)
            } else {
                binding.avatar.setImageResource(R.drawable.default_avatar)
            }
            if (chatRoom.unreadMessages > 0) {
                binding.unreadMsgNumber.text = "[" + chatRoom.unreadMessages + "条未读]"
                binding.unreadMsgNumber.visibility = View.VISIBLE
                binding.unreadMsg.visibility = View.VISIBLE
            } else {
                binding.unreadMsg.visibility = View.GONE
                binding.unreadMsgNumber.visibility = View.GONE
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatRoomViewHolder {
        val itemView = RowChatRoomLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        val viewHolder = ChatRoomViewHolder(itemView)
        return viewHolder
    }

    override fun getItemCount(): Int = chatRoomList.size
    override fun onBindViewHolder(holder: ChatRoomViewHolder, position: Int) {
        val chatRoom = chatRoomList[position]

        with(holder) {
            bind(chatRoom)
            itemView.setOnClickListener{
                mOnItemClickListener?.onItemClick(position)
            }
        }
    }

}